package com.fang.security.common.base;

import com.fang.security.common.exception.RException;
import com.fang.security.common.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @Description
 * @Author Bernie
 * @Date 2024/4/10 17:22
 **/
@ControllerAdvice(basePackages = {"com.fang.security"})
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(value = RException.class)
    public JsonResult returnRunningMyException(RException e) {
        log.error("错误-------------->{}", e.getMessage());
        log.error(this.getTrace(e));
        return JsonResult.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    public JsonResult returnRunningMyException(AccessDeniedException e) {
        log.error("错误-------------->{}", e.getMessage());
        log.error(this.getTrace(e));
        return JsonResult.fail(ServiceCode.INSUFFICIENT_PERMISSIONS);
    }

    /**
     * @param e:
     * @Description: 处理总异常
     * @Author: Bernie_fang
     * @Since: 2021/8/23 12:17
     * @return: com.fang.backgroundapi.common.JsonResult
     **/
    @ExceptionHandler(value = Exception.class)
    public JsonResult returnRunningException(Exception e) {
        log.error("错误-------------->{}", e.getMessage());
        log.error(this.getTrace(e));
        if (e instanceof RException) {
            RException re = (RException) e;
            return JsonResult.fail(re.getCode(), re.getMessage());
        }
        return JsonResult.fail();
    }

    /**
     * @param t: 抛出的错误
     * @Description: 拿到错误的栈堆信息，变成String
     * @Author: Bernie_fang
     * @Since: 2021/8/22 16:37
     * @return: java.lang.String
     **/
    public String getTrace(Throwable t) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }
}
